/*!
// Testweb v0.6.0
// http://or-change.cn
// Copyright 2015 OrChange Inc. All rights reserved.
// Licensed under the GPL License.
*/

/*jslint vars: true, forin: true, plusplus: true */
/*global angular: false, engine: false*/
engine.factory("Dictionary", function (Entity) {
	'use strict';
	/**
	 * Dict tool functions. Factory function.
	 * @class Dictionary.
	 */
	var Dictionary = function Dictionary(options) {
		/**
		 * Cache a builder result in object.
		 * @property data
		 * @type object
		 */
		this.assignment = options.assignment;
		this.field = options.field;
		this.buffer = [];
		Entity.call(this, options);
	};
	Dictionary.prototype = new Entity();
	Dictionary.prototype.constructor = Dictionary;
	/**
	 * 获取一条数据
	 * @method getRow
	 * @param index {number}
	 * @returns row {object}
	 *		dictionary.getRow(0);
	 */
	Dictionary.prototype.getRow = function (index) {
		var key, row = {},
			data = this.data;
		for (key in data) {
			row[key] = data[key][index];
		}
		return row;
	};
	Dictionary.prototype.loading = function (length) {
		var i, len = this.assignment.length,
			keys = this.getKeys(),
			len_of_fields = keys.length;

		var Row = function (row_array) {
			var i;
			for (i = 0; i < len_of_fields; i++) {
				this[keys[i].name] = row_array[i];
			}
		};

		var RandRow = function () {
			var i;
			for (i = 0; i < len_of_fields; i++) {
				this[keys[i].name] = keys[i].pattern.gen;
			}
		};

		// 装填指定值
		for (i = 0; i < len && i < length; i++) {
			this.buffer.push(new Row(this.assignment[i]));
		}
		// 装填随机值
		for (null; i < length; i++) {
			this.buffer.push(new RandRow());
		}

		return this;
	};
	Dictionary.prototype.getKeys = function () {
		var keys = [];
		angular.forEach(this.field, function (field) {
			this.push({
				name: field.name,
				pattern: new RegExp(field.pattern)
			});
		}, keys);

		return keys;
	};
	Dictionary.prototype.fetch = function () {
		return this.buffer.shift();
	};

	return Dictionary;
});
